<template>
  <div class="notification-list-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>我的通知</span>
          <div class="header-actions">
            <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="badge-item">
              <el-button type="primary" @click="handleSend">
                <el-icon><Plus /></el-icon>
                发送通知
              </el-button>
            </el-badge>
            <el-button type="success" @click="handleMarkAllRead" :disabled="unreadCount === 0">
              <el-icon><Check /></el-icon>
              全部已读
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="通知类型">
          <el-select v-model="queryForm.type" placeholder="全部" clearable style="width: 150px">
            <el-option label="系统通知" :value="1" />
            <el-option label="角色通知" :value="2" />
            <el-option label="个人通知" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="阅读状态">
          <el-select v-model="queryForm.unreadOnly" placeholder="全部" clearable style="width: 150px">
            <el-option label="全部" :value="false" />
            <el-option label="仅未读" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input
            v-model="queryForm.title"
            placeholder="请输入通知标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 通知列表 -->
      <el-table
        :data="notificationList"
        border
        style="width: 100%"
        v-loading="loading"
        @row-click="handleRowClick"
        :row-class-name="getRowClassName"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="expand-content">
              <p><strong>通知内容：</strong></p>
              <div class="content-text">{{ row.content }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-badge :is-dot="row.isRead === 0" type="danger">
              <el-icon :size="20" :color="row.isRead === 0 ? '#F56C6C' : '#67C23A'">
                <Bell v-if="row.isRead === 0" />
                <CircleCheck v-else />
              </el-icon>
            </el-badge>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="通知标题" width="250" show-overflow-tooltip />
        <el-table-column label="通知类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ row.typeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="senderName" label="发送者" width="150" />
        <el-table-column prop="createTime" label="发送时间" width="180" />
        <el-table-column label="阅读状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isRead === 1 ? 'success' : 'info'">
              {{ row.isRead === 1 ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="readTime" label="阅读时间" width="180" />
        <el-table-column label="操作" fixed="right" width="180" align="center">
          <template #default="{ row }">
            <el-button
              v-if="row.isRead === 0"
              type="success"
              size="small"
              @click.stop="handleMarkRead(row)"
            >
              标记已读
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click.stop="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 通知详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="通知详情"
      width="700px"
      @close="handleCloseDetail"
    >
      <div v-if="currentNotification" class="notification-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="通知标题" :span="2">
            {{ currentNotification.title }}
          </el-descriptions-item>
          <el-descriptions-item label="通知类型">
            <el-tag :type="getTypeTag(currentNotification.type)">
              {{ currentNotification.typeName }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="发送者">
            {{ currentNotification.senderName }}
          </el-descriptions-item>
          <el-descriptions-item label="发送时间" :span="2">
            {{ currentNotification.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="通知内容" :span="2">
            <div class="content-detail">{{ currentNotification.content }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Check, Search, Refresh, Bell, CircleCheck } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import {
  getMyNotifications,
  markAsRead,
  markAllAsRead,
  deleteNotification,
  getUnreadCount
} from '@/api/notification'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const notificationList = ref([])
const total = ref(0)
const unreadCount = ref(0)
const detailDialogVisible = ref(false)
const currentNotification = ref(null)

// 查询表单
const queryForm = reactive({
  pageNum: 1,
  pageSize: 10,
  type: null,
  unreadOnly: false,
  title: ''
})

// 获取通知列表
const loadNotifications = async () => {
  loading.value = true
  try {
    const res = await getMyNotifications(queryForm)
    if (res.code === 200) {
      notificationList.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取通知列表失败')
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
    ElMessage.error('获取通知列表失败')
  } finally {
    loading.value = false
  }
}

// 获取未读数量
const loadUnreadCount = async () => {
  try {
    const res = await getUnreadCount()
    if (res.code === 200) {
      unreadCount.value = res.data
    }
  } catch (error) {
    console.error('获取未读数量失败:', error)
  }
}

// 查询
const handleQuery = () => {
  queryForm.pageNum = 1
  loadNotifications()
}

// 重置
const handleReset = () => {
  queryForm.type = null
  queryForm.unreadOnly = false
  queryForm.title = ''
  handleQuery()
}

// 发送通知
const handleSend = () => {
  router.push('/notification/send')
}

// 全部标记为已读
const handleMarkAllRead = async () => {
  try {
    const res = await markAllAsRead()
    if (res.code === 200) {
      ElMessage.success('全部标记为已读')
      loadNotifications()
      loadUnreadCount()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('标记失败:', error)
    ElMessage.error('标记失败')
  }
}

// 标记单个为已读
const handleMarkRead = async (row) => {
  try {
    const res = await markAsRead(row.receiverId)
    if (res.code === 200) {
      ElMessage.success('标记为已读')
      loadNotifications()
      loadUnreadCount()
    } else {
      ElMessage.error(res.message || '标记失败')
    }
  } catch (error) {
    console.error('标记失败:', error)
    ElMessage.error('标记失败')
  }
}

// 删除通知
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteNotification(row.receiverId)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadNotifications()
      loadUnreadCount()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 行点击事件
const handleRowClick = async (row) => {
  currentNotification.value = row
  detailDialogVisible.value = true
  
  // 如果未读，自动标记为已读
  if (row.isRead === 0) {
    await markAsRead(row.receiverId)
    loadNotifications()
    loadUnreadCount()
  }
}

// 关闭详情对话框
const handleCloseDetail = () => {
  currentNotification.value = null
}

// 获取行类名（未读行高亮）
const getRowClassName = ({ row }) => {
  return row.isRead === 0 ? 'unread-row' : ''
}

// 获取类型标签
const getTypeTag = (type) => {
  const typeMap = {
    1: 'info',      // 系统通知
    2: 'warning',   // 角色通知
    3: 'success'    // 个人通知
  }
  return typeMap[type] || ''
}

// 页面加载
onMounted(() => {
  loadNotifications()
  loadUnreadCount()
})
</script>

<style scoped>
.notification-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.badge-item {
  margin-right: 10px;
}

.query-form {
  margin-bottom: 20px;
}

.expand-content {
  padding: 20px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.content-text {
  margin-top: 10px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-all;
  color: var(--el-text-color-primary);
}

.content-detail {
  line-height: 1.8;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 400px;
  overflow-y: auto;
  color: var(--el-text-color-primary);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.unread-row) {
  background-color: var(--el-color-primary-light-9);
  font-weight: 500;
}

:deep(.unread-row:hover) {
  background-color: var(--el-color-primary-light-8) !important;
}

.notification-detail {
  padding: 10px 0;
}

/* 深色模式适配 */
html.dark .expand-content {
  background-color: var(--el-fill-color-darker);
}

html.dark :deep(.unread-row) {
  background-color: rgba(64, 158, 255, 0.1);
}

html.dark :deep(.unread-row:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important;
}
</style>

